package com.resou.reader.mine;

import android.app.AlertDialog;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.entry.VersionBean;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.mine.login.LoginFragment;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.SystemUtil;
import com.resou.reader.utils.downupdata.DownloadListener;
import com.resou.reader.utils.downupdata.DownloadUtil;
import com.resou.reader.utils.log.LogUtil;
import com.resou.reader.view.CircleImageView;

import org.raphets.roundimageview.RoundImageView;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Author: 萤火虫
 * E-mail:  Allensuns@163.com
 * Description: 我的模块的Presenter层
 * CreateTime: 2019-04 -08
 **/
public class HomeUserCenterPresenter extends ResouBasePresenter<IHomeUserCenterInterface.IHomeUserCenterView> implements IHomeUserCenterInterface.IHomeUserCenterPresenter {
    private static final String TAG = "HomeUserCenterPresenter";
    UserService userService;
    ProgressBar mProgressBar;

    public HomeUserCenterPresenter(IHomeUserCenterInterface.IHomeUserCenterView view) {
        super(view);
        userService = ApiImp.getInstance().getService(UserService.class);
    }


    /**
     * 判断用户是否登录
     *
     * @param fragmentManager
     * @return
     */
    @Override
    public boolean isAlreadyLogin(FragmentManager fragmentManager) {
        boolean isAlreadyLogin = UserInstance.isLogin();
        if (!isAlreadyLogin) {
            LoginFragment.getInstance().setLoginListener((LoginListener) mView);
            LoginFragment.getInstance().show(fragmentManager, "LoginFragment");
        }
        return isAlreadyLogin;
    }

    /**
     * 更新用户信息
     *
     * @param loginData
     * @param mHeadIv
     * @param mNameTv
     * @param tvHotTicket
     * @param tvHotMoney
     */
    @Override
    public void initUserInfo(LoginData loginData, RoundImageView mHeadIv, TextView mNameTv, TextView tvHotTicket, TextView tvHotMoney) {
        if (!TextUtils.isEmpty(UserInstance.getToken())) {
            String headPic = loginData.getHead_pic();
            PreferenceUtil.getInstance(mView.getContent().getActivity()).saveSubSidyStateValue(loginData.getReadType());

            if (!TextUtils.isEmpty(headPic)) {
                RequestOptions options = new RequestOptions();
                options.format(DecodeFormat.PREFER_RGB_565);
                Glide.with(mView.getContent()).load(loginData.getHead_pic()).apply(options).into(mHeadIv);
            }
            if (!TextUtils.isEmpty(loginData.getNickName())) {
                mNameTv.setTextColor(mView.getContent().getResources().getColor(R.color.color_ff333333));
                mNameTv.setText(loginData.getNickName());
            } else {
                String phoneNumber = loginData.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                mNameTv.setText(phoneNumber);
                mNameTv.setTextColor(mView.getContent().getResources().getColor(R.color.color_ffd53d2d));
            }
            tvHotTicket.setText((int) loginData.getGiftBlance() + "");
            tvHotMoney.setText((int) loginData.getBlance() + "");
            if (1 == loginData.getIsVipUser()) {
                mView.userVipState(true);
            } else {
                mView.userVipState(false);
            }
        } else {
            tvHotTicket.setText("0");
            tvHotMoney.setText("0");
            RequestOptions options = new RequestOptions();
            options.format(DecodeFormat.PREFER_RGB_565);
            Glide.with(mView.getContent()).load(R.mipmap.user_head).apply(options).into(mHeadIv);
        }
    }

    @Override
    public void updataView(boolean isLogin, RelativeLayout rlLogined, RelativeLayout rlLook) {
        if (isLogin) {
            rlLogined.setVisibility(View.VISIBLE);
            rlLook.setVisibility(View.GONE);
        } else {
            rlLogined.setVisibility(View.GONE);
            rlLook.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 版本更新
     */
    @Override
    public void updataVersion() {
        userService.checkVersionUpdata().subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<Result<VersionBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(Result<VersionBean> result) {
                        if (result.getCode() == 0) {
                            if (result.getData().getVersion_code() > SystemUtil.getVersionCode(mView.getContent().getActivity())) {
                                mView.showUpdata(result.getData().getApk_url());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void showUpdataDialog(AlertDialog dialog, AlertDialog.Builder builder, String downUrl) {
        if (null == builder) {
            builder = new AlertDialog.Builder(mView.getContent().getActivity(), R.style.DialogStyle);
            View view = LayoutInflater.from(mView.getContent().getActivity()).inflate(R.layout.dialog_updataprogress, null);
            builder.setView(view);
            dialog = builder.create();

            RelativeLayout rlUpdataView = view.findViewById(R.id.rlUpdataView);
            RelativeLayout rlShowUpdata = view.findViewById(R.id.rlShowUpdata);
            ImageView ivClose = view.findViewById(R.id.ivClose);
            TextView tvClose = view.findViewById(R.id.tvClose);
            TextView tvProgress = view.findViewById(R.id.tvProgress);
            ImageButton ibtnUpdata = view.findViewById(R.id.ibtnUpdata);
            mProgressBar = view.findViewById(R.id.mProgressBar);
            dialog.setCanceledOnTouchOutside(false);
            ibtnUpdata.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    rlUpdataView.setVisibility(View.VISIBLE);
                    rlShowUpdata.setVisibility(View.GONE);
                    downApk(downUrl, tvProgress);
                }
            });
            AlertDialog finalDialog = dialog;
            ivClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).setIsUpdateApp(false);
                    finalDialog.dismiss();
                }
            });
            tvClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finalDialog.dismiss();
                }
            });
        }
        dialog.show();
    }


    /**
     * 版本更新
     *
     * @param url
     */
    @Override
    public void downApk(String url, TextView tvProgress) {
        String path = Environment.getExternalStorageDirectory().getPath().toString();
        DownloadUtil.download(url, path, new DownloadListener() {
            @Override
            public void onStart() {
                LogUtil.d(TAG, "开始下载");
            }

            @Override
            public void onProgress(int progress) {
                mView.getContent().getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressBar.setProgress(progress);
                        tvProgress.setText(progress + "%");
                    }
                });
            }

            @Override
            public void onFinish(String path) {
                LogUtil.d(TAG, path);
                mView.InstallApk(path);
            }

            @Override
            public void onFail(String errorInfo) {
//                ToastUtil.makeShortToast(errorInfo);
                LogUtil.d(TAG, errorInfo);
            }
        });
    }


}
